package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author fenglin
 * @date 2019/12/10 21:13
 */
@Service
public class SpecService {
    @Autowired
    private SpecGroupMapper specGroupMapper;
    @Autowired
    private SpecParamMapper specParamMapper;
    public List<SpecGroupDTO> querySpecGroupByCategory(Long id) {
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(id);
        List<SpecGroup> select = specGroupMapper.select(specGroup);
        //非空判断
        if (CollectionUtils.isEmpty(select)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        //转换为DTO
        List<SpecGroupDTO> list = BeanHelper.copyWithCollection(select, SpecGroupDTO.class);
        return list;
    }

    public List<SpecParamDTO> queryParams(Long gid, Long cid, Boolean searching) {
        // 健壮性处理
        if (gid == null && cid == null) {
            // 没有查询参数，返回400
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        SpecParam specParam = new SpecParam();
        specParam.setGroupId(gid);
        specParam.setCid(cid);
        specParam.setSearching(searching);
        List<SpecParam> select = specParamMapper.select(specParam);
        //非空判断
        if (CollectionUtils.isEmpty(select)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        //转换为DTO
        List<SpecParamDTO> specParamDTOS = BeanHelper.copyWithCollection(select, SpecParamDTO.class);
        return specParamDTOS;
    }


    /**
     * 根据商品分类id查询规格组及规格参数
     * @param id 分类id
     * @return 组及组内参数
     */
    public List<SpecGroupDTO> querySpecList(Long id) {
        // 根据分类id查询group的集合
        List<SpecGroupDTO> groupList = querySpecGroupByCategory(id);
        // 查询出分类下的所有参数
        List<SpecParamDTO> params = queryParams(null, id, null);
        // 把params按照groupId做分组，groupId一致的放到一个集合。变成一个map，key是groupId,值是param集合
        Map<Long, List<SpecParamDTO>> map = params.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        // 根据groupId查询参数
        for (SpecGroupDTO group : groupList) {
            group.setParams(map.get(group.getId()));
        }
        return groupList;
    }

}
